package com.heima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.heima.api.ItemClient;
import com.heima.domain.dto.PageDto;
import com.heima.domain.query.ItemPageQuery;
import com.heima.domain.vo.FiltersVo;
import com.heima.dto.ItemDTO;
import com.heima.dto.PageItemDto;
import com.heima.service.SearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ItemClient itemClient;

    @Override
    public void initData() throws IOException {
        int currentPage = 1;
        boolean isNext = true;
        while (isNext) {
            // 分页查询
            PageItemDto pageItemDto = itemClient.queryPages(currentPage);
            List<ItemDTO> list = pageItemDto.getItemDTOS();
            // 创建 BulkRequest     WriteRequest.RefreshPolicy.IMMEDIATE : 刷新策略立即刷新
            BulkRequest bulkRequest = new BulkRequest().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);

            for (ItemDTO record : list) {
                // 创建Request 并添加到BulkRequest
                IndexRequest items = new IndexRequest("items").id(record.getId().toString());
                // 封装DSL语句
                items.source(JSONUtil.toJsonStr(record), XContentType.JSON);
                //并添加到BulkRequest
                bulkRequest.add(items);
            }
            //执行请求
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

            currentPage++;
            // currentPage > 总页数 就不执行循环
            if (currentPage > pageItemDto.getTotalPage()) {
                isNext = false;
            }
        }
    }

    @Override
    public PageDto<ItemDTO> esSearch(ItemPageQuery query) throws IOException {
        //1、 创建 SearchRequest
        SearchRequest searchRequest = new SearchRequest("items");
        //2、创建 BoolQueryBuilder
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //3、在boolQuery封装组合条件
        if (query.getKey() != null && query.getKey() != "") {
            boolQuery.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if (query.getCategory() != null && query.getCategory() != "") {
            boolQuery.must(QueryBuilders.matchQuery("category", query.getCategory()));
        }
        if (query.getBrand() != null && query.getBrand() != "") {
            boolQuery.must(QueryBuilders.matchQuery("brand", query.getBrand()));
        }
        if (query.getMinPrice() != null && query.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()));
        }
        boolQuery.filter(QueryBuilders.matchQuery("status", 1));
        // 竞价排名 FunctionScoreQueryBuilder
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery
                ,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true)
                                ,
                                ScoreFunctionBuilders.weightFactorFunction(10f)
                        )
                }
        ).boostMode(CombineFunction.SUM);
        // 把 FunctionScoreQueryBuilder 加入到 SearchRequest
        searchRequest.source().query(functionScoreQueryBuilder);
        // 开启高亮
        searchRequest.source().highlighter(new HighlightBuilder()
                .field("name")
                .preTags("<em style=\"color:red;\">")
                .postTags("</em>")
        );
        // 排序（es默认按分数排序 "_score" ）
        if(StrUtil.isNotEmpty(query.getSortBy())){
            searchRequest.source().sort(query.getSortBy(), SortOrder.ASC);
        }
        // 分页
        searchRequest.source().from(query.getPageNo() - 1).size(query.getPageSize());
        // 执行查询
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 总条数
        long total = searchResponse.getHits().getTotalHits().value;
        // 封装
        PageDto pageItemDto = new PageDto<ItemDTO>();
        pageItemDto.setTotal(total);
        //                      类型转换
        pageItemDto.setList(parseResult(searchResponse));
        //                      分页总页数计算
        pageItemDto.setPages(total % query.getPageSize()==0 ? total / query.getPageSize() : (total / query.getPageSize())+1);
        return pageItemDto;
    }

    /**
     * 结果集类型转换
     * 将非高亮转换为高亮
     */
    public List<ItemDTO> parseResult(SearchResponse searchResponse) {
        List<ItemDTO> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            // 7、1 获取非高亮数据
            ItemDTO itemDTO = JSONUtil.toBean(hit.getSourceAsString(), ItemDTO.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!CollectionUtil.isEmpty(highlightFields)){
                // 7、2 高亮数据-非高亮替换成高亮
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField != null){
                    String result = StrUtil.join("..", highlightField.getFragments());
                    // 7、3 非高亮替换成高亮
                    itemDTO.setName(result);
                }
            }
            list.add(itemDTO);
        }
        return list;
    }

    @Override
    public Map<String,List<String>> filters(FiltersVo filtersVo) throws IOException {
        SearchRequest searchRequest = new SearchRequest("items");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(filtersVo.getKey() != null && filtersVo.getKey() != ""){
            boolQuery.must(QueryBuilders.matchQuery("name", filtersVo.getKey()));
        }
        boolQuery.filter(QueryBuilders.termQuery("status",1));
        searchRequest.source().query(boolQuery);
        //分组查询【根据品牌过滤】
        searchRequest.source().aggregation(
                AggregationBuilders
                        // 聚合查询类型 term 按照词条分组查询
                        // brandAggs:别名，给当前聚合查询取个别名
                        .terms("brandAggs")
                        // 分组得字段
                        .field("brand")
                        .size(20)
        );
        //分组查询【根据分类过滤】
        searchRequest.source().aggregation(
                AggregationBuilders
                        // 聚合查询类型 term 按照词条分组查询
                        // brandAggs:别名，给当前聚合查询取个别名
                        .terms("categoryAggs")
                        // 分组得字段
                        .field("category")
                        .size(20)
        );
        searchRequest.source().from(filtersVo.getPageNo()).size(filtersVo.getPageSize());
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        Map<String,List<String>> result = parseFilterCondtions(searchResponse);
        return result;
    }

    /**
     * 过滤条件解析
     */
    private static Map<String,List<String>> parseFilterCondtions(SearchResponse searchResponse){
        //1、获取aggregations
        Aggregations aggregations = searchResponse.getAggregations();
        //2、根据别名取出每个分组数据集合
        //2.1、brandAggs得数据
        ParsedStringTerms brandAggs = aggregations.get("brandAggs");
        List<String> brands = brandAggs.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
        //2.2、categotyAggs得数据
        ParsedStringTerms categotyAggs = aggregations.get("categoryAggs");
        List<String> categoty = categotyAggs.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
        //3、返回数据
        Map<String,List<String>> resultMap = new HashMap<>();
        resultMap.put("brand",brands);
        resultMap.put("category",categoty);
        return resultMap;
    }
}
